package cn.lzg.server.module.user.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.lzg.common.core.exception.ErrorCodeException;
import cn.lzg.common.core.model.Result;
import cn.lzg.common.core.model.ResultCode;
import cn.lzg.common.core.session.Session;
import cn.lzg.common.module.user.request.LoginRequest;
import cn.lzg.common.module.user.request.RegisterRequest;
import cn.lzg.common.module.user.response.UserResponse;
import cn.lzg.server.module.user.service.UserService;

@Component
public class UserHandlerImpl implements UserHandler {
	@Autowired
	private UserService userService;
	
	@Override
	public Result<UserResponse> login(Session session, byte[] bytes) {
		UserResponse response = null;
		try {
			// 反序列化，得到登陆的请求对象
			LoginRequest request = new LoginRequest();
			request.readFromBytes(bytes);

			System.out.println(request.getId());
			// 参数判空
			/*
			 * if (StringUtils.isEmpty(request.getId()) ||
			 * StringUtils.isEmpty(request.getPassword())) { return
			 * Result.ERROR(ResultCode.AGRUMENT_ERROR); }
			 */
			// 交给业务层处理
			response = userService.login(session, request.getId(), request.getPassword());
			System.out.println(response.getAvatar().getFilename());
		} catch (ErrorCodeException e) {
			return Result.ERROR(e.getErrorCode());
		} catch (Exception e) {
			e.printStackTrace();
			return Result.ERROR(ResultCode.UNKOWN_EXCEPTION);
		}
		Result<UserResponse> success = Result.SUCCESS(response);
		System.out.println(success);
		return success;
	}

	@Override
	public Result<UserResponse> register(Session session, byte[] bytes) {
		UserResponse response = null;

		try {
			// 反序列化
			RegisterRequest request = new RegisterRequest();
			request.readFromBytes(bytes);

			// 判定规格
			if (request.getUserId() == null || request.getPassword().isEmpty()) {
				throw new ErrorCodeException(ResultCode.AGRUMENT_ERROR);
			}

			// 逻辑处理
			response = userService.register(session, request.getUserId(), request.getPassword());

		} catch (ErrorCodeException e) {
			return Result.ERROR(e.getErrorCode());
		} catch (Exception e) {
			e.printStackTrace();
			return Result.ERROR(ResultCode.UNKOWN_EXCEPTION);
		}
		return Result.SUCCESS(response);
	}

}
